<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v25;

use app\api\controller\v2\Auth;
use app\common\cachemodel\MapUnlockResult;
use app\common\cachemodel\OrdersGoods;
use app\common\cachemodel\zl4\Zl4UserDataTypeStatus;
use app\common\cachemodel\ZlVisit;
use app\common\lib\astrolog\Acg;
use app\common\lib\exception\ApiException;
use app\common\lib\PushQueue;
use app\common\lib\Util;
use app\common\model\AppLogicVersion;
use app\common\model\FateCity;
use app\common\model\Goods;
use app\common\model\Map as MapModel;
use app\common\model\Map as MapRecode;
use app\common\model\Recode;
use app\common\model\SystemLogicVersion;
use think\Cache;
use think\exception\DbException;

/**
 * @title ACG地图相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class Map extends Auth
{
    protected $visitType = 2;

    /**
     * 幸运之城首页
     * @return \think\response\Json|bool
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作');
        }

        $rid = input('get.rid/d');

        if (!$rid)
        {
            return show(config('code.error'), '档案不存在');
        }

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }
        //获取用户当前已解锁的数据
        $unlockInfo = (new MapRecode())->getRecodeUnlockLines($recode, true);
        $lines = $unlockInfo['lines'];
        $planets = $unlockInfo['planets'];
        $recalculation_info = $unlockInfo['recalculation_info'];

        $i = 0;
        foreach ($planets['planet1'] as $k => $d)
        {
            if ($i >= 11)
            {
                continue;
            }// 仅过滤需要绘制的11颗星的数据中，未解锁购买的

            if ($lines['data'][$i] == 0)
            {
                unset($planets['planet1'][$k], $planets['planet2'][$k]);
            }
            $i++;
        }

        $line_list = (new MapRecode())->getLineList($this, $lines['data']);// 所有命格线商品

        if ($this->is_apple_pay)
        {
            $advertising = [
                'is_open' => false,
                'content' => '',
            ];
        } else
        {
            $advertising = config('map.advertising');
        }

        $fate_city = [];
        //无需更新
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => $lines['status']
        ];
        //计算中的弹窗开关
        $is_underway = $lines['status'] === 2 ? 1 : 0;
        // 计算命运之城数据
        if ($lines['data'][11] == 1 && $lines['status'] != 2)
        {
            $info = [
                'uid' => (int)$this->user['id'],
                'rid' => $rid,// 档案id
                'sex' => $recode['type'],// 档案性别
                'isself' => $recode['isself'],
                'longitude' => ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'],// 用户出生地经度
                'latitude' => ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'],// 用户出生地纬度
                'time' => strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute'])
                    - ($recode['timezone'] + $recode['is_summer']) * 3600,// 用户出生时间
            ];
            //0=>最新逻辑，无需更新，1=》逻辑需要更新，2=》逻辑计算中
            if ($lines['status'] != 2)
            {
                $fate_city = (new FateCity())->getUserFateCitys($info);
            }

            if (!$fate_city)
            {
                $is_underway = 1;
            }

            //获取当前最新版本逻辑信息
            $SystemLogicModel = new SystemLogicVersion();
            $logic_data = $SystemLogicModel->getVersion(['type' => 1]);
            //获取当前档案逻辑版本号
            $AppLogicModel = new AppLogicVersion();
            $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 1]);

            //更新中
            if (!$fate_city || Cache::get($this->user['id'] . ':' . $rid . '_acg_logic_status'))
            {
                $update_logic = [
                    'title' => '',
                    'content' => '',
                    'status' => 2,
                ];
            } //待更新
            elseif ($logic_data['version'] && $user_logic < $logic_data['version'])
            {
                $update_logic = [
                    'title' => $logic_data['title'],
                    'content' => $logic_data['content'],
                    'status' => 1,
                ];
            }
//            $advertising['is_open'] = false;// 判断商品全部解锁后就关闭喇叭
        }

        if ($advertising['is_open'] === true && $lines['data'] === '111111111111')
        {
            $advertising['is_open'] = false;
        }// 后台控制喇叭关闭

        //弹窗信息 0=>不展示更新按钮；1=》逻辑更新；2=》计算中；3=》档案修改后更新；4=》修改档案不可更新；【根据status 判断弹框类型】
        $alert_info = $recalculation_info ?: $update_logic;
        //版本2.9.6以后,档案修改的提示状态更新为按钮更新状态
        if (isset($alert_info['status']) && Util::CheckAppVersion('2.9.6') !== '小')
        {
            if ($alert_info['status'] == 4)
            {
                $alert_info['status'] = 0;
            }
        }
        if (in_array(19, $unlockInfo['unlock_gids'], false) && Util::CheckAppVersion('2.9.6') !== '小')
        {
            $userDataTypeStatusModel = new Zl4UserDataTypeStatus();
            $statusInfo = $userDataTypeStatusModel->getUserDataTypeStatus((int)$recode['uid'], 'map_update_notify');
            if (!($statusInfo && $statusInfo['status'] === 1))
            {
                $popInfo = [
                    'title' => '- 幸运地图免费升级通知 -',
                    'content' => '幸运地图升级啦～为了感谢小行星对准了的支持，我们将对所有升级前打包解锁命格线的小行星免费开放城市排行功能，您已获得城市排行免费使用权限，感谢对准了的支持！',
                    'btn_txt' => '查看城市排行'
                ];
                $userDataTypeStatusModel->setUserDataTypeStatus((int)$recode['uid'], 'map_update_notify', 1);
            }
        }

        $result = [
            'lines_list' => $line_list,
            'planet1' => $planets['planet1'] ?? null,
            'planet2' => $planets['planet2'] ?? null,
            'fate_city' => $fate_city,
            'advertising' => (object)$advertising,
            'help_url' => config('map.help_url'),
            'is_alert' => false, // TODO 弹窗信息未做
            'is_underway' => $is_underway,
            'alert_info' => $alert_info ?: null,
            'pack_and_unlock' => $unlockInfo['pack_and_unlock'] ?? null,
            'pop_info' => $popInfo ?? null,
            'tab_list' => $unlockInfo['tab_list'] ?? null,
        ];

        $distinctId = $this->request->header('distinct-id', '');
        if ($distinctId)
        {
            $result['is_first'] = (new ZlVisit())->getVisitData($this->user['id'], $this->visitType);
        }

        return show(config('code.success'), '加载成功', $result);
    }

    /**
     * 幸运之城重新计算
     * @return \think\response\Json
     * @throws \Exception
     */
    public function recalculationMap()
    {
        $rid = input('rid/d', 0);
        if (!$rid)
        {
            return show(config('code.error'), '请求异常');
        }
        //获取用户当前已解锁的数据
        $unlockIds = (new MapUnlockResult())->getUnlockIdsFromCache(3, $rid);
        $unlockInfos = (new MapUnlockResult())->batchGetInfoByIds($unlockIds, ['order_id']);
        $max_data = (new MapRecode())->getNewCityUnlockData($unlockInfos);
        if ($max_data)
        {
            (new PushQueue())->Map($max_data['order_id'], false, ['status' => 1, 'last_calculation_time' => time()]);
        }
        return show(config('code.success'), '操作成功');
    }

    public function mapHistory()
    {
        $orderId = input('get.order_id/s');
        $rid = input('get.rid/d', 0);

        if (!$orderId)
        {
            return show(config('code.error'), '订单不存在');
        }

        $orderInfo = current((new \app\common\cachemodel\Orders())->batchGetInfo($orderId, ['id']));
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$orderInfo['id']])) ?: [];
        $rids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $rids[] = $og['rid'];
        }

        $rid = $rid && in_array($rid, $rids, false) ? $rid : current($rids);

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }

        //获取用户当前已解锁的数据
        $unlockInfo = (new MapRecode())->getRecodeUnlockLines($recode, true);
        $lines = $unlockInfo['lines'];
        $planets = $unlockInfo['planets'];

        $i = 0;
        foreach ($planets['planet1'] as $k => $d)
        {
            if ($i >= 11)
            {
                continue;
            }// 仅过滤需要绘制的11颗星的数据中，未解锁购买的

            if ($lines['data'][$i] == 0)
            {
                unset($planets['planet1'][$k], $planets['planet2'][$k]);
            }
            $i++;
        }
        if ($this->is_apple_pay)
        {
            $acg_goods = $this->apple_goods['acg_goods'];
        } else
        {
            $acg_goods = (new Goods())->getGoodsForACG();
        }

        // 从配置文件中加载相关配置
        $config = config('map');

        $line_list = [];// 所有命格线商品

        foreach ($acg_goods as $ag)
        {

            if ($ag['id'] > 18)
            {
                continue;
            }// 只需要11条线的数据

            $discount = (float)$ag['discount'];// 折扣

            $price = $discount ? $ag['or_prize'] * $discount : $ag['now_prize'];// 计算实际价格

            //商品折扣活动
            $activeDiscount = active($ag['id']);
            if ($activeDiscount['discount'])
            {
                $price *= $activeDiscount['discount'];
            }

            $is_unlock = $lines['data'][$ag['id'] - 7] == 1;
            if (!$is_unlock)
            {
                continue;
            }


            $tmp = [
                'gid' => $ag['id'],
                'name' => $ag['name'],
                'price' => sprintf('%.2f', $price),
                'icon' => $config['lines_icon'][$ag['id']],
                'description' => $config['lines_title'][$ag['id']],
                'color' => $config['lines_color'][$ag['id']],
                'is_unlock' => $is_unlock,
                'pid' => $config['pid'][$ag['id']],
                'planet' => $config['planet'][$ag['id']],
                'point_title' => $config['point_title'][$ag['id']],
                'point_des' => $config['point_des'][$ag['id']],
            ];

            if ($ag['id'] == 18)
            {
                $tmp['description'] = '这是在中国境内，对你生活起居某方面最为有利的大城市，能对你不同方面起到良好的改善作用。（此处只有国内一、二、三线城市，后续会持续更新国内其他小城市和国外城市的计算，所以你的命运之城可能会随着升级会有改变。）解锁后对每一座命运之城都有详细解读。';
            }

            $line_list[] = $tmp;
        }
        $line_list = resort($line_list, 'is_unlock');// 布尔值进行排序，暂未发现问题????

        $fate_city = [];

        //计算中的弹窗开关
        $is_underway = 0;
        // 计算命运之城数据
        if ($lines['data'][11] == 1)
        {
            $info = [
                'uid' => (int)$this->user['id'],
                'rid' => $rid,// 档案id
                'sex' => $recode['type'],// 档案性别
                'isself' => $recode['isself'],
                'longitude' => ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'],// 用户出生地经度
                'latitude' => ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'],// 用户出生地纬度
                'time' => strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute'])
                    - ($recode['timezone'] + $recode['is_summer']) * 3600,// 用户出生时间
            ];
            //0=>最新逻辑，无需更新，1=》逻辑需要更新，2=》逻辑计算中
            if ($lines['status'] != 2)
            {
                $fate_city = (new FateCity())->getUserFateCitys($info);
            }

            if (!$fate_city)
            {
                $is_underway = 1;
            }

        }

        $result = [
            'lines_list' => $line_list,
            'planet1' => $planets['planet1'] ?? null,
            'planet2' => $planets['planet2'] ?? null,
            'fate_city' => $fate_city,
            'help_url' => config('map.help_url'),
            'is_underway' => $is_underway,
            'long_deg' => $recode['long_deg'],
            'long_min' => $recode['long_min'],
            'lat_deg' => $recode['lat_deg'],
            'lat_min' => $recode['lat_min'],
            'ew' => $recode['ew'],
            'ns' => $recode['ns'],
        ];

        $distinctId = $this->request->header('distinct-id', '');
        if ($distinctId)
        {
            $result['is_first'] = (new ZlVisit())->getVisitData($this->user['id'], $this->visitType);
        }

        return show(config('code.success'), '加载成功', $result);
    }

    /**
     * ACG地点详情
     * @return \think\response\Json
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function mapDetailHistory()
    {
        if (!request()->isGet()) return show(config('code.error'), '未知操作', [], 403);

        $type = input('get.type');// 地点类型
        $rid = input('get.rid');// 档案id

        $orderId = input('get.order_id/s');

        if (!$orderId)
        {
            return show(config('code.error'), '订单不存在');
        }

        $orderInfo = current((new \app\common\cachemodel\Orders())->batchGetInfo($orderId, ['id']));
        $maps_goods = current((new OrdersGoods())->batchGetInfo([$orderInfo['id']])) ?: [];
        $rids = [];
        foreach ($maps_goods as $order_good)
        {
            $og = json_decode($order_good, true);
            $rids[] = $og['rid'];
        }

        $rid = $rid && in_array($rid, $rids, false) ? $rid : current($rids);


        if (!$rid) return show(config('code.error'), '档案不存在');

        $current_longitude = input('get.current_longitude');// 所在位置经纬度

        $current_latitude = input('get.current_latitude');// 所在位置经纬度

        $point_longitude = input('get.point_longitude');// 选择点的经纬度

        $point_latitude = input('get.point_latitude');// 选择点的经纬度

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);

        $timestamp = strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute']);

        $timestamp -= ($recode['timezone'] + $recode['is_summer']) * 3600;

        $longitude = ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'];

        $latitude = ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'];

        $info = [
            'type' => $type,// 1=>普通地点，2=>命运之地
            'rid' => $rid,// 档案id
            'current_longitude' => $current_longitude,// 当前所在位置经度
            'current_latitude' => $current_latitude,// 当前所在位置纬度
            'point_longitude' => $point_longitude,// 选择的点的经度
            'point_latitude' => $point_latitude,// 选择的点的纬度
            'longitude' => $longitude,// 用户出生地经度
            'latitude' => $latitude,// 用户出生地纬度
            'time' => $timestamp,// 用户出生时间
            'sex' => $recode['type'],// 档案性别
            'isself' => $recode['isself'],// 当前档案是否为自己，检查是否有赠送记录，计算命格线对地点的影响
            'uid' => $this->user['id'],// 用户id
        ];

        $validate = validate('Map');

        if (!$validate->scene('read')->check($info)) return show(config('code.error'), (string)$validate->getError());
        // 获取选中地点分值
        $array = (new Acg())->getRecommendedInfo($info);
        // 获取选中地点收藏状态
        $collect_status = (new MapModel())->checkCollectStatus(['latitude' => $point_latitude, 'longitude' => $point_longitude, 'uid' => $this->user['id'], 'rid' => $rid]);

        $array['is_collect'] = $collect_status['is_collect'];
        $array['collect_id'] = $collect_status['collect_id'];

        if ($type == 2) $array['type'] = true;

        return show(config('code.success'), '加载成功', $array);
    }
}
